let express = require('express');
let router = express.Router();

const checkJWTMiddleWare = require('../middleWare/checkJWTMiddleWare');

// 此路由需要登录后才能访问
router.use(checkJWTMiddleWare);

// 实体类
const Response = require('../entity/http/Response');
const UserInfo = require('../entity/user/UserInfo');
const Img64 = require('../entity/file/Img64');

// 配置
const config = require('../config');

// 业务层
const userinfoService = require('../service/userinfoService');

/*
 * 获取个人信息接口
 */
router.get('/getUserInfo', async function(req, res, next) {
    let { uid } = req.jwtResult.data;
    userinfoService.getUserInfo(uid).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("获取个人信息失败"));
    });
});

/*
 * 修改个人信息接口
 */
router.post('/updateUserInfo', async function(req, res, next) {
    let { uid } = req.jwtResult.data;
    let userInfo = new UserInfo(req);
    let flag = userInfo.check();
    if (!flag.success) {
        return res.status(400).json(flag);
    }
    userinfoService.updateUserInfo(uid, userInfo).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("修改个人信息失败"));
    });
});

/*
 * 获取 专注时长、投递数、收藏数 的接口
 */
router.get('/getHomePageNeedData', async function(req, res, next) {
    let { uid } = req.jwtResult.data;
    userinfoService.getHomePageNeedData(uid).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("获取 专注时长、投递数、收藏数 信息失败"));
    });
});

/*
 * 上传用户头像接口
 */
router.post('/updateUserIcon', async function (req, res, next) {
    let { uid } = req.jwtResult.data;
    let img64 = new Img64(req.body, config.user.avatarImgMaxSize);
    let flag = img64.check();
    if (!flag.success) {
        return res.status(400).json(flag);
    }
    userinfoService.updateUserIcon(uid, img64.buffer).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("上传用户头像失败"));
    });
});

module.exports = router;